package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
     RedisTemplate redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDto dto) {
     // 1.校验参数判断前端传进来的数据
     //根据作者信息获取到关联的用户信息
        if (dto.getAuthorApUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "您需要关注的作者对应用户不存在");
        }
     // 2.校验关注类型是否出错
        Short operation = dto.getOperation();
        if (operation == null || (operation.intValue() != 0 && operation.intValue() != 1)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "n您关注的类型有误");
        }
        // 3.从线程中获取到该用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        //判断用户是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "该操作需要登录账号");
        }
     // 4.获取到该用户的id，判断该用户关注的id是不是自己
        Integer userId = user.getId();
        Integer followId = dto.getAuthorApUserId();
        if (userId.equals(followId)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿关注自己");
        }
        // 5.判断用户是否已经关注该作者
        Double score = redisTemplate.opsForZSet()
                .score(UserRelationConstants.FANS_LIST + userId, String.valueOf(followId));
        if (operation.intValue() == 0 && score != null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "已关注，请勿重复关注");
        }
        // 6.开启redis的事务
        redisTemplate.multi();
     // 判断operation是0  是1
        if (operation.intValue() == 0) {
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(followId), System.currentTimeMillis());
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + followId, String.valueOf(userId), System.currentTimeMillis());
        }
     // 0关注   1取消关注
        if (operation.intValue() == 1) {
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(followId), System.currentTimeMillis());
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + followId, String.valueOf(userId), System.currentTimeMillis());
        }
        redisTemplate.exec();
        return ResponseResult.okResult();
    }
}
